<template>
  <el-dialog :visible.sync="dialogVisible" title="选择服务地址" width="800px" @close="onClose">
    <div style="margin-bottom: 10px;">
      <el-autocomplete
        v-model="searchKeyword"
        :fetch-suggestions="querySearch"
        placeholder="请输入地址关键词"
        @select="handleSelect"
        :key="dialogVisible"
        style="width: 400px"
      />
      <el-button @click="searchPlace">搜索</el-button>
    </div>
    <div id="amap-container" style="width: 100%; height: 400px;"></div>
    <div style="margin-top: 10px;">
      <el-input v-model="address" placeholder="选中的地址" readonly />
    </div>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="confirmSelect" :disabled="!address">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: 'MapSelector',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      address: '',
      longitude: '',
      latitude: '',
      searchKeyword: '',
      map: null,
      marker: null,
      geocoder: null,
      autoComplete: null,
      placeSearch: null
    };
  },
  watch: {
    modelValue(val) {
      this.dialogVisible = val;
      if (val) {
        this.address = '';
        this.searchKeyword = '';
        this.$nextTick(this.initMap);
      }
    },
    dialogVisible(val) {
      if (!val) {
        this.$emit('update:modelValue', false);
      }
    }
  },
  methods: {
    onClose() {
      this.dialogVisible = false;
    },
    confirmSelect() {
      this.$emit('select', {
        address: this.address,
        longitude: this.longitude,
        latitude: this.latitude
      });
      this.onClose();
    },
    initMap() {
      if (this.map) {
        this.map.destroy();
        this.map = null;
        this.marker = null;
      }
      this.map = new window.AMap.Map('amap-container', {
        zoom: 12,
        center: [116.397428, 39.90923]
      });
      // 加载插件
      window.AMap.plugin(['AMap.Geocoder', 'AMap.AutoComplete', 'AMap.PlaceSearch'], () => {
        this.geocoder = new window.AMap.Geocoder();
        this.autoComplete = new window.AMap.AutoComplete();
        this.placeSearch = new window.AMap.PlaceSearch({ map: this.map });
        console.log('插件已加载', this.autoComplete);
      });
      // 地图点击选点
      this.map.on('click', (e) => {
        const lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
        if (!this.marker) {
          this.marker = new window.AMap.Marker({
            position: lnglat,
            map: this.map
          });
        } else {
          this.marker.setPosition(lnglat);
        }
        this.longitude = lnglat[0];
        this.latitude = lnglat[1];
        if (this.geocoder) {
          this.geocoder.getAddress(lnglat, (status, result) => {
            if (status === 'complete' && result.regeocode) {
              this.address = result.regeocode.formattedAddress;
            } else {
              this.address = '';
            }
          });
        }
      });
    },
    // 自动补全建议
    querySearch(queryString, cb) {
      console.log('自动补全输入：', queryString, this.autoComplete);
      if (!this.autoComplete) return cb([]);
      if (!queryString) return cb([]);
      this.autoComplete.search(queryString, (status, result) => {
        console.log('自动补全结果：', status, result);
        if (status === 'complete' && result.tips) {
          // 转换为el-autocomplete需要的格式
          const tips = result.tips
            .filter(item => item.location)
            .map(item => ({
              ...item,
              value: item.name // 关键：加上value字段
            }));
          cb(tips);
        } else {
          cb([]);
        }
      });
    },
    // 选中建议
    handleSelect(item) {
      if (item.location) {
        this.map.setCenter(item.location);
        if (!this.marker) {
          this.marker = new window.AMap.Marker({
            position: item.location,
            map: this.map
          });
        } else {
          this.marker.setPosition(item.location);
        }
        this.longitude = item.location.lng;
        this.latitude = item.location.lat;
        if (this.geocoder) {
          this.geocoder.getAddress([item.location.lng, item.location.lat], (status, result) => {
            if (status === 'complete' && result.regeocode) {
              this.address = result.regeocode.formattedAddress;
            } else {
              this.address = '';
            }
          });
        }
      }
    },
    // 搜索按钮
    searchPlace() {
      if (!this.placeSearch) return;
      this.placeSearch.search(this.searchKeyword, (status, result) => {
        if (status === 'complete' && result.poiList.pois.length > 0) {
          const poi = result.poiList.pois[0];
          this.map.setCenter(poi.location);
          if (!this.marker) {
            this.marker = new window.AMap.Marker({
              position: poi.location,
              map: this.map
            });
          } else {
            this.marker.setPosition(poi.location);
          }
          this.address = poi.address || poi.name;
        }
      });
    }
  }
};
</script>